import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _40_组合总和II {
    @Test
    public void test(){
        System.out.println(combinationSum2(new int[]{2, 5, 2, 1, 2}, 5));
    }
    private List<List<Integer>> result =new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //给数组排序
        Arrays.sort(candidates);
        backtrack(candidates,new ArrayList<>(),0,target,0);
        return result;
    }

    public void backtrack(int[] candidates,List<Integer> path,int pathNum,int target,int sartIndex){

        if (pathNum==target){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i =sartIndex ; i < candidates.length; i++) {
            if (pathNum+candidates[i]<=target){
                path.add(candidates[i]);
                backtrack(candidates,path,pathNum+candidates[i],target,i+1);
                path.remove(path.size()-1);
            }
            //注意避免数组越界的问题
            while (i!=candidates.length-1&&candidates[i]==candidates[i+1]){
                i++;
            }
        }
    }




}